<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="店铺名称" prop="shopName">
        <el-input
          v-model="queryParams.shopName"
          placeholder="请输入店铺名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺类型" prop="shopType">
        <el-input
          v-model="queryParams.shopType"
          placeholder="请输入店铺类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺状态" prop="shopStatus">
        <el-select v-model="queryParams.shopStatus" placeholder="请选择状态" clearable>
          <el-option label="正常营业" :value="1" />
          <el-option label="暂停营业" :value="2" />
          <el-option label="已关闭" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="verifyStatus">
        <el-select v-model="queryParams.verifyStatus" placeholder="请选择审核状态" clearable>
          <el-option label="待审核" :value="0" />
          <el-option label="已通过" :value="1" />
          <el-option label="已拒绝" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:shops:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:shops:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:shops:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:shops:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="shopsList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="shopId" width="80" />
      <el-table-column label="店铺图片" align="center" min-width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.shopImages && formatImageList(scope.row.shopImages).length > 0" style="display: flex; justify-content: center; gap: 5px;">
            <el-image
              v-for="(img, index) in formatImageList(scope.row.shopImages).slice(0, 3)"
              :key="index"
              :src="img"
              :preview-src-list="formatImageList(scope.row.shopImages)"
              style="width: 40px; height: 40px; border-radius: 4px;"
              fit="cover"
            />
            <span v-if="formatImageList(scope.row.shopImages).length > 3">+{{ formatImageList(scope.row.shopImages).length - 3 }}</span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺名称" align="center" prop="shopName" min-width="150" show-overflow-tooltip />
      <el-table-column label="店铺类型" align="center" prop="shopType" width="100" />
      <el-table-column label="店主" align="center" prop="ownerName" width="100" />
      <el-table-column label="评分" align="center" prop="shopRating" width="100">
        <template slot-scope="scope">
          <el-rate v-model="scope.row.shopRating" disabled show-score text-color="#ff9900" />
        </template>
      </el-table-column>
      <el-table-column label="地址" align="center" prop="shopAddress" min-width="200" show-overflow-tooltip />
      <el-table-column label="店铺状态" align="center" prop="shopStatus" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.shopStatus === 1" type="success" size="small">正常营业</el-tag>
          <el-tag v-else-if="scope.row.shopStatus === 2" type="warning" size="small">暂停营业</el-tag>
          <el-tag v-else-if="scope.row.shopStatus === 0" type="info" size="small">已关闭</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="verifyStatus" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.verifyStatus === 0" type="warning" size="small">待审核</el-tag>
          <el-tag v-else-if="scope.row.verifyStatus === 1" type="success" size="small">已通过</el-tag>
          <el-tag v-else-if="scope.row.verifyStatus === 2" type="danger" size="small">已拒绝</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:shops:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:shops:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改店铺管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="店铺名称" prop="shopName">
                  <el-input v-model="form.shopName" placeholder="请输入店铺名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="店铺类型" prop="shopType">
                  <el-input v-model="form.shopType" placeholder="请输入店铺类型" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="店铺描述" prop="shopDescription">
                  <el-input 
                    v-model="form.shopDescription" 
                    type="textarea"
                    :rows="4"
                    placeholder="请输入店铺描述"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="店铺图片" prop="shopImages">
                  <image-upload 
                    v-model="form.shopImages" 
                    :limit="9"
                    :fileSize="5"
                    :isShowTip="true"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="评分" prop="shopRating">
                  <el-rate v-model="form.shopRating" show-text />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="营业执照" prop="businessLicense">
                  <el-input v-model="form.businessLicense" placeholder="请输入营业执照号" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 位置信息 -->
          <el-tab-pane label="位置信息" name="location">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="店铺位置" prop="shopLocation">
                  <el-input v-model="form.shopLocation" placeholder="请输入店铺位置" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="店铺坐标" prop="shopCoordinates">
                  <el-input v-model="form.shopCoordinates" placeholder="例如：经度,纬度" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="详细地址" prop="shopAddress">
                  <el-input v-model="form.shopAddress" placeholder="请输入店铺详细地址" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="shopPhone">
                  <el-input v-model="form.shopPhone" placeholder="请输入店铺联系电话" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="营业时间" prop="shopOpenTime">
                  <el-input v-model="form.shopOpenTime" placeholder="如：9:00-21:00" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 店主信息 -->
          <el-tab-pane label="店主信息" name="owner">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="店主ID" prop="ownerId">
                  <el-input v-model="form.ownerId" placeholder="请输入店主用户ID" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="店主姓名" prop="ownerName">
                  <el-input v-model="form.ownerName" placeholder="请输入店主姓名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="店主手机号" prop="ownerPhone">
                  <el-input v-model="form.ownerPhone" placeholder="请输入店主手机号" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 状态设置 -->
          <el-tab-pane label="状态设置" name="status">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="店铺状态" prop="shopStatus">
                  <el-select v-model="form.shopStatus" placeholder="请选择状态" style="width: 100%">
                    <el-option label="正常营业" :value="1" />
                    <el-option label="暂停营业" :value="2" />
                    <el-option label="已关闭" :value="0" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="审核状态" prop="verifyStatus">
                  <el-select v-model="form.verifyStatus" placeholder="请选择审核状态" style="width: 100%">
                    <el-option label="待审核" :value="0" />
                    <el-option label="已通过" :value="1" />
                    <el-option label="已拒绝" :value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="店铺等级" prop="shopLevel">
                  <el-input-number v-model="form.shopLevel" :min="1" :max="5" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 扩展信息 -->
          <el-tab-pane label="扩展信息" name="extra">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="店铺分类" prop="shopCategory">
                  <el-input 
                    v-model="form.shopCategory" 
                    type="textarea" 
                    :rows="3"
                    placeholder='请输入JSON格式，例如：["美食","餐饮"]'
                  />
                  <span class="form-tip">* 请输入合法的JSON数组格式</span>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="扩展数据" prop="extraData">
                  <el-input 
                    v-model="form.extraData" 
                    type="textarea"
                    :rows="5"
                    placeholder='请输入JSON格式的扩展数据'
                  />
                  <span class="form-tip">* 请输入合法的JSON格式数据</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listShops, getShops, delShops, addShops, updateShops } from "@/api/system/shops";
import ImageUpload from '@/components/ImageUpload';

export default {
  name: "Shops",
  components: {
    ImageUpload
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      shopsList: [],
      title: "",
      open: false,
      activeTab: 'basic',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shopName: null,
        shopType: null,
        shopDescription: null,
        shopImages: null,
        shopCategory: null,
        shopTags: null,
        shopLocation: null,
        shopCoordinates: null,
        shopOpenTime: null,
        shopPhone: null,
        shopAddress: null,
        ownerId: null,
        ownerPhone: null,
        ownerName: null,
        shopRating: null,
        shopCommentIds: null,
        shopCommentCount: null,
        shopGoodReviews: null,
        shopBadReviews: null,
        shopActivityIds: null,
        shopLikeCount: null,
        shopLikeIds: null,
        shopCheckInCount: null,
        shopCheckInIds: null,
        businessLicense: null,
        shopStatus: null,
        verifyStatus: null,
        shopFollowers: null,
        shopViews: null,
        shopSales: null,
        shopLevel: null,
        shopNotice: null,
        shopFeatures: null,
        shopPromotions: null,
        status: null,
        extraData: null,
        createdAt: null,
        updatedAt: null
      },
      form: {},
      rules: {
        shopName: [
          { required: true, message: "店铺名称不能为空", trigger: "blur" }
        ],
        shopType: [
          { required: true, message: "店铺类型不能为空", trigger: "blur" }
        ],
        ownerId: [
          { required: true, message: "店主用户ID不能为空", trigger: "blur" }
        ],
        ownerName: [
          { required: true, message: "店主姓名不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    formatImageList(images) {
      if (!images) return [];
      try {
        const imageArray = typeof images === 'string' ? JSON.parse(images) : images;
        return Array.isArray(imageArray) ? imageArray : [];
      } catch (e) {
        return [];
      }
    },
    getList() {
      this.loading = true;
      listShops(this.queryParams).then(response => {
        this.shopsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        shopId: null,
        shopName: null,
        shopType: null,
        shopDescription: null,
        shopImages: null,
        shopCategory: null,
        shopTags: null,
        shopLocation: null,
        shopCoordinates: null,
        shopOpenTime: null,
        shopPhone: null,
        shopAddress: null,
        ownerId: null,
        ownerPhone: null,
        ownerName: null,
        shopRating: 5.0,
        shopCommentIds: null,
        shopCommentCount: 0,
        shopGoodReviews: 0,
        shopBadReviews: 0,
        shopActivityIds: null,
        shopLikeCount: 0,
        shopLikeIds: null,
        shopCheckInCount: 0,
        shopCheckInIds: null,
        businessLicense: null,
        shopStatus: 1,
        verifyStatus: 0,
        shopFollowers: 0,
        shopViews: 0,
        shopSales: 0,
        shopLevel: 1,
        shopNotice: null,
        shopFeatures: null,
        shopPromotions: null,
        status: null,
        extraData: null,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.shopId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.activeTab = 'basic';
      this.open = true;
      this.title = "添加店铺";
    },
    handleUpdate(row) {
      this.reset();
      this.activeTab = 'basic';
      const shopId = row.shopId || this.ids
      getShops(shopId).then(response => {
        this.form = response.data;
        
        // 处理图片字段
        if (this.form.shopImages) {
          const urls = typeof this.form.shopImages === 'string' 
            ? JSON.parse(this.form.shopImages) 
            : this.form.shopImages;
          this.form.shopImages = Array.isArray(urls) ? urls.join(',') : urls;
        }
        
        // 处理JSON字段
        const jsonFields = ['shopCategory', 'shopTags', 'status', 'extraData'];
        for (const field of jsonFields) {
          if (this.form[field] && typeof this.form[field] === 'object') {
            this.form[field] = JSON.stringify(this.form[field], null, 2);
          }
        }
        
        this.open = true;
        this.title = "修改店铺";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitForm = JSON.parse(JSON.stringify(this.form));
          
          // 处理图片字段
          if (submitForm.shopImages && typeof submitForm.shopImages === 'string') {
            const urlArray = submitForm.shopImages.split(',').filter(url => url.trim());
            submitForm.shopImages = urlArray.length > 0 ? JSON.stringify(urlArray) : null;
          }
          
          // 处理JSON字段
          const jsonFields = ['shopCategory', 'shopTags', 'status', 'extraData'];
          for (const field of jsonFields) {
            if (submitForm[field] && typeof submitForm[field] === 'string') {
              try {
                submitForm[field] = submitForm[field].trim() 
                  ? JSON.parse(submitForm[field]) 
                  : null;
              } catch (e) {
                this.$modal.msgError(`${field}字段JSON格式不正确`);
                return;
              }
            }
          }
          
          if (submitForm.shopId != null) {
            updateShops(submitForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addShops(submitForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const shopIds = row.shopId || this.ids;
      this.$modal.confirm('是否确认删除店铺编号为"' + shopIds + '"的数据项？').then(function() {
        return delShops(shopIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('system/shops/export', {
        ...this.queryParams
      }, `shops_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
  display: block;
}

::v-deep .el-tabs--border-card {
  box-shadow: none;
}

::v-deep .el-tabs__content {
  padding: 20px;
}
</style>
